package com.stary.pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.StringUtils;
import com.stary.pay.alipay.config.IAlipayConfig;
import com.stary.pay.alipay.util.AlipayUtils;

/**
 * <p>初始化支付宝请求客户端</p>
 * @author stary {@link stary1993@qq.com}
 * @since 2018-11-1
 */
public class InitAlipayClient {
	/**
	 * 服务请求网关url
	 */
	private static final String SERVER_URL="https://openapi.alipay.com/gateway.do";
	
	/**
	 * 支付宝配置接口
	 */
	private IAlipayConfig aliPayConfig;

	public InitAlipayClient(IAlipayConfig aliPayConfig) {
		super();
		this.aliPayConfig = aliPayConfig;
	}

	public IAlipayConfig getAliPayConfig() {
		return aliPayConfig;
	}

	public void setAliPayConfig(IAlipayConfig aliPayConfig) {
		this.aliPayConfig = aliPayConfig;
	}

	/**
	 * 创建客户端
	 * @return {@link AlipayClient}
	 * @throws AlipayApiException 
	 */
	public AlipayClient build() throws AlipayApiException {
		if (StringUtils.isEmpty(aliPayConfig.appId()) || StringUtils.isEmpty(aliPayConfig.privateKey())
				|| StringUtils.isEmpty(aliPayConfig.alipayPublicKey())) {
			throw new AlipayApiException("alipay config appId or privateKey or alipayPublicKey must not null");
		}
		AlipayClient alipayClient = new DefaultAlipayClient(SERVER_URL, aliPayConfig.appId(), aliPayConfig.privateKey(),
				AlipayConstants.FORMAT_JSON, AlipayConstants.CHARSET_UTF8, aliPayConfig.alipayPublicKey(), AlipayConstants.SIGN_TYPE_RSA2);
		AlipayUtils.getLogger().info("build AlipayClient succeed");
		return alipayClient;
	}

}
